package com.songlin.testv2ex.model;

import android.util.Log;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.regex.Pattern;

/**
 * Created by 松林 on 2015/10/5.
 */
public class TopicsList extends ArrayList<Topic> implements Serializable{
    public int currPage = 1;
    public int totalPage = 1;

    public void parse(String responseBody) throws Exception {
        Document document = Jsoup.parse(responseBody);
        Element body = document.body();
        Elements elements = body.getElementsByAttributeValue("class", "cell item");
        for (Element e: elements) {
            try {
                Topic topic = parseTopic(e, true, null);
                add(topic);
            } catch(Exception ex) {
                Log.d("Throws Exception", "Catch Exception From parse(String responseBody) in Topic.java");
                ex.printStackTrace();
            }
        }
        parsePage(body);
    }

    public void parseFromNodeEntry(String responseBody,String nodeName) throws Exception {
        Document document = Jsoup.parse(responseBody);
        String title = document.title();
        title = title.replace("V2EX ›", "").trim();
        title = title.split(" ")[0];
        Node node = new Node();
        node.name = nodeName;
        node.title = title;

        Element body = document.body();
        Elements elements = body.getElementsByAttributeValueMatching("class", Pattern.compile("cell_from(.*)"));
    }

    private void parsePage(Element body) {
        Elements elements = body.getElementsByAttributeValue("class", "inner");
        for (Element element:elements) {
            Elements tds = element.getElementsByTag("td");  //每个<inner>标签里的<td>标签对数
            if (tds.size() != 3)
                continue;
            String pageString = element.getElementsByAttributeValue("align","center").text();
            pageString = pageString.split(" · ")[0];
            String[] arrayString = pageString.split("/");
            if (arrayString.length != 2)
                continue;
            try {
                currPage = Integer.parseInt(arrayString[0]);
                totalPage = Integer.parseInt(arrayString[1]);
            } catch (Exception ex) {
                Log.d("Throws Exception", "From \"private void parsePage(Element body)\" in TopicsList.java");
                ex.printStackTrace();
            }
            break;
        }
    }

    public Topic parseTopic(Element e,boolean parseNode,Node node) throws Exception {
        Elements tdNodes = e.getElementsByTag("td");
        Topic topic = new Topic();
        Member member = new Member();
        if(parseNode) {
            node = new Node();
        }
        for (Element elementTd:tdNodes) {
            String contentTd = elementTd.toString();
            if(contentTd.contains("class=\"avatar\"")) {
                Elements elementsA = elementTd.getElementsByTag("a");
                if(elementsA != null) {
                    String idUrlString = elementsA.attr("href");
                    member.username = idUrlString.replace("/member/", "");
                }

                Elements elementsAvatarImg = elementTd.getElementsByTag("img");
                if(elementsAvatarImg != null) {
                    String avatarString = elementsAvatarImg.attr("src");
                    if (avatarString.startsWith("//")) {
                        avatarString = "http:" + avatarString;
                    }
                    member.avatar = avatarString;
                }
            } else if(contentTd.contains("class\"item_title\"")) {
                Elements elementsTitle = elementTd.getElementsByTag("a");
                for (Element elementTitle: elementsTitle) {
                    if ( parseNode && elementTitle.attr("class").equals("node") ) {
                        String nodeUrlString = elementTitle.attr("href");
                        node.name = nodeUrlString.replace("/go/", "");
                        node.title = elementTitle.text();
                    } else {
                        if(elementTitle.toString().contains("reply") ) {
                            topic.title = elementTitle.text();
                            String TopicIdString = elementTitle.attr("href");
                            String[] subArray = TopicIdString.split("#");
                            topic.id = Integer.parseInt(subArray[0].replace("/t/",""));
                            topic.replies = Integer.parseInt(subArray[1].replace("reply",""));
                        }
                    }
                }

                Elements elementsSpan = elementTd.getElementsByTag("span");
                for (Element elementSpan :elementsSpan) {
                    String contentSpan = elementSpan.text();
                    if (contentSpan.contains("最后回复") || contentSpan.contains("前") || contentSpan.contains("  •  ")){
                        String[] components = contentSpan.split("  •  ");
                        if(parseNode && components.length <= 2)
                            continue;
                        else if(!parseNode && components.length <= 1)
                            continue;
                        String dateString = parseNode ? components[2] : components[1] ;
                        long currentTime = System.currentTimeMillis() / 1000;   //以秒为单位
                        long created = currentTime;
                        String[] stringArray = dateString.split(" ");
                        if (stringArray.length > 1) {
                            String unitString = "";
                            try {
                                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                                Date date = simpleDateFormat.parse(dateString); //转化为Date类格式的时间
                                 currentTime = date.getTime() / 1000;    //以秒为单位，自1970年1月1日00:00:00 GMT已经过去的秒
                                topic.created = currentTime;
                                break;
                            } catch(Exception ex) {
                                Log.d("Throws Exception","Catch Exception From parseTopic(Element e,boolean parseNode,Node node) in Topic.java");
                                ex.printStackTrace();
                            }
                            int number = Integer.parseInt(stringArray[0]); //stringArray就是时间段中空格前的数字
                            String subString = stringArray[1].substring(0,1);
                            if (subString.equals("分")) {
                                unitString = "分钟前";
                                created = currentTime - 60 * number;
                            } else if(subString.equals("小")) {
                                unitString = "小时前";
                                created = currentTime -  3600 * number;
                            } else if (subString.equals("天")) {
                                unitString = "天";
                                created = currentTime - 86400 * number;
                            }
                            dateString = String.format("%s%s",stringArray[0],unitString);
                        } else {
                            dateString = "刚刚";
                        }
                        topic.created = created;
                    }
                }
            }
        }
        topic.member = member;
        topic.node = node;
        return topic;
    }
}
